import { defineStore } from 'pinia';

const STORAGE_KEY = 'superdb-settings';

export const useConfigStore = defineStore('config', {
  state: () => ({
    apiKey: '',
    baseUrl: import.meta.env.VITE_API_BASE || '/api',
    embeddingsProvider: 'mock',
    temperature: 0.2,
    topK: 4,
    initialized: false
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.apiKey?.trim()),
    authHeaders: (state) => (state.apiKey ? { 'x-api-key': state.apiKey } : {})
  },
  actions: {
    loadFromStorage() {
      if (this.initialized) return;
      try {
        const payload = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
        if (payload.apiKey) this.apiKey = payload.apiKey;
        if (payload.embeddingsProvider) this.embeddingsProvider = payload.embeddingsProvider;
        if (payload.temperature !== undefined) this.temperature = payload.temperature;
        if (payload.topK !== undefined) this.topK = payload.topK;
      } catch (error) {
        console.warn('Failed to parse local settings', error);
      }
      this.initialized = true;
    },
    setApiKey(key) {
      this.apiKey = key.trim();
      this.persist();
    },
    setEmbeddingsProvider(provider) {
      this.embeddingsProvider = provider;
      this.persist();
    },
    setTemperature(value) {
      this.temperature = value;
      this.persist();
    },
    setTopK(value) {
      this.topK = value;
      this.persist();
    },
    reset() {
      this.apiKey = '';
      this.persist();
    },
    persist() {
      const payload = {
        apiKey: this.apiKey,
        embeddingsProvider: this.embeddingsProvider,
        temperature: this.temperature,
        topK: this.topK
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
    }
  }
});
